package org.example.learn.javassist.reloadClass;


import com.sun.jdi.connect.IllegalConnectorArgumentsException;
import javassist.*;
import javassist.util.HotSwapper;


import java.io.IOException;

// 修改正在运行class文件内容
public class ReloadClass {

    public static void main(String[] args) throws IOException, NotFoundException, CannotCompileException, IllegalConnectorArgumentsException {

//        final RandomNumber randomNumber = new RandomNumber();

        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    System.out.println(new RandomNumber().randomNumber());
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        String className = RandomNumber.class.getName();
        System.out.println(className);
        // java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000
        // 使用此方法需要引入 jdk安装目录下的lib文件夹内的tools.jar
        HotSwapper hs = new HotSwapper(8000);

        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass = pool.get(className);

        // 获取目标类方法
        CtMethod ctMethod = ctClass.getDeclaredMethod("randomNumber");
        // 重写方法
        ctMethod.setBody("{return 0;}");

        System.out.println("执行HotSwapper热插拔");
        // 重新装载目标class文件
        hs.reload("org.example.learn.javassist.reloadClass.RandomNumber",ctClass.toBytecode());
    }
}
